package org.chnxi.study.concurrent.future;

import java.util.concurrent.*;

public class FutureDemo {

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
//        ThreadPoolExecutor executorService = new ThreadPoolExecutor(1,1,1000 , TimeUnit.SECONDS , new ArrayBlockingQueue<>(32)){
//            @Override
//            protected void afterExecute(Runnable r, Throwable t) {
//                super.afterExecute(r, t);
//            }
//        };

        Future<Integer> future = executorService.submit(() -> {
            int num = (int) (Math.random() * 1000);
            try {
                TimeUnit.MILLISECONDS.sleep(num);
                if(num % 2 == 0){
                    //异常就会被包装成ExecutionException异常抛出。
                    throw new RuntimeException("模拟异常发生");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return num;
        });

        TimeUnit.MILLISECONDS.sleep(1);

        System.out.println("已经发送执行任务，主线程可继续执行。。。");
        try {
            Integer result = future.get();
            System.out.println("获取到的结果："+result);
        } catch (InterruptedException e) {
            System.out.println("InterruptedException>>>"+e.getMessage());
        } catch (ExecutionException e) {
            if(e.getCause() != null && e.getCause() instanceof RuntimeException){
                System.out.println("ExecutionException>>>"+e.getCause().getMessage());
            }else{
                e.printStackTrace();
            }
        } catch (RuntimeException e){
            // 此处获取不到异常，已经不是RuntimeException类型
            System.out.println("此处获取异常："+e.getMessage());
        } finally {
            executorService.shutdown();
        }
    }

}
